package com.WOWTradeNews;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.WOWTradeNews.DataBase.ConstValues;
import com.WOWTradeNews.DataBase.DBManager;
import com.WOWTradeNews.DataBase.News;
import com.WOWTradeNews.DataBase.NewsDataBase;
import com.WOWTradeNews.DataBase.SystemDBManager;
import com.WOWTradeNews.phone.TradeNewsPhone;
import com.WOWTradeNews.services.AD;
import com.WOWTradeNews.services.NewsServer;
import com.WOWTradeNews.tablet.TradeNews;
import com.WOWTradeNewsTest.R;

public class Loading extends Activity implements Runnable {
	private NewsDataBase newsDataBase;
	private final static String NEWS_TXT_PATH = "http://210.241.128.49/App/trade_news.txt";
	private final static String NEWS_DB_PATH = "http://210.241.128.49/App/trade_news.sqlite";

//	private final static String NEWS_TXT_PATH = "http://wowtrade.perfect.tw/App/trade_news.txt";//for test
//	private final static String NEWS_DB_PATH = "http://wowtrade.perfect.tw/App/trade_news.sqlite";//for test
 
	private ProgressBar myProgressBar;
	int myProgress = 0;
	public static int limitDipWidth;
	
	private Thread mThread;
	private Button pauseButton;
	
	private boolean runFlag;
	private DBManager dbManager;
	private SystemDBManager systemDBManager;
	private DBManager tempDbManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		limitDipWidth = (int)(dm.widthPixels / dm.density);
		
		if (limitDipWidth >= 47900) {
			setContentView(R.layout.loading_large);
		} else {
			setContentView(R.layout.loading);
		}
		
		myProgressBar = (ProgressBar) findViewById(R.id.progressbar);
		pauseButton   = (Button) findViewById(R.id.pause);
		
		mThread = null;
		dbManager = new DBManager(Loading.this, ConstValues.DB_NEWS);
		systemDBManager = new SystemDBManager(Loading.this);
		tempDbManager = new DBManager(Loading.this, ConstValues.DB_TEMP);
		
		pauseButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(true) {
					runFlag = false;
					Log.d("zhaosdfa", "pause---suc------>>>>");
					//mThread.interrupt();
					Log.d("zhaosdfa", "pause---suc------>>>>");
					//chooseDisplay();
					Log.d("zhaosdfa", "pause---suc------>>>>");
				}
			}
		});

		try {
			newsDataBase = new NewsDataBase(this);
			newsDataBase.createDataBase();
			newsDataBase.close();
		} catch (Exception e) {
			e.getStackTrace();
		}

		if (isConnect(Loading.this) == false) {
			Context context = this;
			int duration = Toast.LENGTH_SHORT;
			//Toast toast = Toast.makeText(context, "無網路連結!!", duration);
			AlertDialog.Builder builder = new AlertDialog.Builder(Loading.this);
			builder.setTitle("提示");
			builder.setMessage("無網路連結!");
			builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					chooseDisplay();
				}
			});
			builder.show();
			//toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 200);
			//toast.show();

			//chooseDisplay();
		} else {
			myProgressBar.setProgress(myProgress);
			runFlag = true;
			mThread = new Thread(this);
			mThread.start();
		}
	}

	@Override
	public void run() {
		/*try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}*/
		runFlag = true;
		down_Json();
		//checkNewsDBVersion();
		handler.sendEmptyMessage(0);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("zhaosdfa", "handle------>>>>");
			chooseDisplay();
			Log.d("zhaosdfa", "handle------>>>>");
		}
	};

	public void checkNewsDBVersion() {
		Cursor newsCursor = null;
		try {
			newsCursor = newsDataBase.selectVersionCode();
			if (newsCursor != null) {
				newsCursor.moveToFirst();
			}
			String DataBaseVersion = newsCursor.getString(newsCursor.getColumnIndex("ver"));

			URL url = new URL(NEWS_TXT_PATH);
			URLConnection conn;
			conn = url.openConnection();
			conn.connect();

			InputStream is = conn.getInputStream();
			String InputStreamVersion = convertStreamToString(is);

			float dbVersion = Float.parseFloat(DataBaseVersion);
			float isVersion = Float.parseFloat(InputStreamVersion);

			System.out.println("dbVersion=" + dbVersion + "/isVersion="+ isVersion);

			if (dbVersion < isVersion) {
				URL dataBaseUrl = new URL(NEWS_DB_PATH);
				URLConnection dataBaseConn = dataBaseUrl.openConnection();
				dataBaseConn.connect();

				InputStream dataBaseOnCloud = dataBaseConn.getInputStream();
				String outFileName = NewsDataBase.DATABASE_TEMP_FILE_PATH+ NewsDataBase.NEWS_DATABASE_NAME;

				OutputStream dataBaseInPhone = new FileOutputStream(outFileName);

				byte[] buffer = new byte[1024];
				int length;
				while ((length = dataBaseOnCloud.read(buffer)) > 0) {
					dataBaseInPhone.write(buffer, 0, length);
				}
				dataBaseInPhone.flush();
				dataBaseInPhone.close();
				dataBaseOnCloud.close();

				copyNewsDB();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (newsCursor != null && !newsCursor.isClosed())
				newsCursor.close();
			newsDataBase.close();
		}
	}
	
	public void down_Json() {
		List<News> adList = null;
		
		try {
			adList = AD.getAdList();
		} catch (Exception e1) {
			e1.printStackTrace();
			Log.e("zhaosdfa", "Update Ad error:" + e1.toString());
			//Toast.makeText(Loading.this, "Update Ad error!", 0).show();
		}
		if(!runFlag) {
			dbManager.closeDB();
			return;
		}
		Log.d("zhaosdfa", "AdList---suc------>>>>");
		TreeSet<String> set = new TreeSet<String>();
		List<List<News> > allList = new ArrayList<List<News> >();
		for(int i=2; i<=6 && runFlag; i++) {
			try {
				List<News> list = NewsServer.getNewsList(i);
				//allList.add(list);
				for(News n : list) {
					String iid = n.getIid();
					set.add(iid);
					if(dbManager.findByIid(iid) == null) {
						if(n.getImg1Url() != null && !n.getImg1Url().equals("")) {
							n.setImg(Utils.getUrlBitmapBonus(n.getImg1Url()));
						}
						dbManager.addNews(n);
					}
				}
				Log.d("zhaosdfa", "new" + i + "List---suc------>>>>");
			} catch (Exception e) {
				e.printStackTrace();
				//Toast.makeText(Loading.this, "error", 1).show();
			}
		}
		if(!runFlag)  {
			dbManager.closeDB();
			return;
		}
		
		
		/*int sum = 0;
		for(List<News> l : allList) {
			if(l != null) {
				sum += l.size();
			}
		}
		if(sum > 0) {
			dbManager.delateAllNews();
			for(List<News> l : allList) {
				if(l != null) {
					dbManager.addNews(l);
				}
			}
		}*/
		dbManager.deleteOthers(set);
		if(adList != null && adList.size() > 0) {
			dbManager.deleteTypeNews(ConstValues.NEWS_TYPE_AD);
			dbManager.addNews(adList);
		}
		Log.d("zhaosdfa", "ad---suc------>>>>");
		Log.d("zhaosdfa", "news---suc------>>>>");
		dbManager.closeDB();
		Log.d("zhaosdfa", "all---suc------>>>>");
	}

	public void copyNewsDB() throws IOException {
		this.deleteDatabase(ConstValues.DB_NEWS);

		InputStream myInput = new FileInputStream(ConstValues.DB_PATH + ConstValues.DB_TEMP);
		String outFileName = ConstValues.DB_PATH + ConstValues.DB_NEWS;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		File file = new File(NewsDataBase.DATABASE_TEMP_FILE_PATH+ NewsDataBase.NEWS_DATABASE_NAME);
		file.delete();

		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public String convertStreamToString(InputStream is) throws IOException {
		if (is != null) {
			Writer writer = new StringWriter();
			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	public static boolean isConnect(Activity activity) {
		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null)
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		return flag;
	}

	public void chooseDisplay() {
		if (limitDipWidth >= 47900) {
			startActivity(new Intent(Loading.this, TradeNews.class));
			finish();
		} else {
			startActivity(new Intent(Loading.this, TradeNewsPhone.class));
			finish();
		}
	}
	
	@Override
	public void onDestroy() {
		dbManager.closeDB();
		super.onDestroy();
	}
}
